<?php

namespace Modules\Agent\Http\Controllers\Admin\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Modules\Agent\Entities\Agent;
use Modules\Agent\Exports\AgentExport;

use Auth;
use Validator;
use ThrowException;

use Cache;

class AgentExportController extends Controller
{
    public function total(Request $req)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $options = $req->all();
        $options['where'] = [
            ['direct_invitees_count', '>', 0]
        ];
        $total = Agent::getBuilder($options)->count();

        return [
            'total' => $total
        ];
    }

    public function store(Request $req)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();


        $uuid = str_random(30);

        $cached = $req->all();

        Cache::put($uuid, $cached, 10);

        return [
        	'url' => '/admin-api/export/agent/' . $uuid
        ]; 
    }

    public function show(Request $req, $uuid)
    {
    	$rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $cached = Cache::get($uuid) ?: ThrowException::Conflict('未找到缓存内容');

        // $cached['per_page'] = 1000000;

        $cached['builder'] = Agent::where('direct_invitees_count', '>', 0);
        
        $orders = Agent::getList($cached)->list;

        $file = '分销员导出.xlsx';
        return (new AgentExport($orders))->download($file); 
    }
}
